document.addEventListener('DOMContentLoaded', function() {
    loadUsers();
    setupEventListeners();
});

let currentPage = 1;
const perPage = 10;

function loadUsers(page = 1) {
    const membership = document.getElementById('membershipFilter').value;
    const status = document.getElementById('statusFilter').value;
    const search = document.getElementById('searchInput').value;

    fetch(`/api/users?page=${page}&per_page=${perPage}&membership=${membership}&status=${status}&search=${search}`)
        .then(response => response.json())
        .then(data => {
            renderUsers(data.users);
            renderPagination(data.pages, data.current_page);
        })
        .catch(error => {
            console.error('Error loading users:', error);
            showAlert('加载用户数据失败，请稍后重试', 'danger');
        });
}

function renderUsers(users) {
    const tbody = document.getElementById('userTableBody');
    tbody.innerHTML = '';

    users.forEach((user, index) => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${(currentPage - 1) * perPage + index + 1}</td>
            <td>${user.username}</td>
            <td>${user.email}</td>
            <td>${user.phone || '-'}</td>
            <td>${user.membership_level}</td>
            <td>${user.consumption_score ? user.consumption_score.toFixed(1) : '-'}</td>
            <td>
                <span class="badge bg-${user.status ? 'success' : 'secondary'}">
                    ${user.status ? '活跃' : '非活跃'}
                </span>
            </td>
            <td>
                <div class="btn-group">
                    <button class="btn btn-sm btn-outline-primary edit-user" data-id="${user.id}" aria-label="编辑用户">
                        <i class="mdi mdi-pencil"></i>
                    </button>
                    <a href="/user-profile/${user.id}" class="btn btn-sm btn-outline-info" aria-label="查看用户档案">
                        <i class="mdi mdi-account-details"></i>
                    </a>
                    <button class="btn btn-sm btn-outline-danger delete-user" data-id="${user.id}" aria-label="删除用户">
                        <i class="mdi mdi-delete"></i>
                    </button>
                </div>
            </td>
        `;
        tbody.appendChild(tr);
    });
}

function renderPagination(totalPages, currentPage) {
    const pagination = document.getElementById('pagination');
    pagination.innerHTML = '';

    if (totalPages <= 1) {
        return;
    }

    // Previous button
    const prevLi = document.createElement('li');
    prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
    prevLi.innerHTML = `
        <a class="page-link" href="#" data-page="${currentPage - 1}" ${currentPage === 1 ? 'tabindex="-1" aria-disabled="true"' : ''} aria-label="上一页">
            <i class="mdi mdi-chevron-left" aria-hidden="true"></i>
        </a>
    `;
    pagination.appendChild(prevLi);

    // 计算要显示的页码范围
    let startPage = Math.max(1, currentPage - 2);
    let endPage = Math.min(totalPages, startPage + 4);
    
    // 调整startPage确保始终显示5个页码（如果有）
    if (endPage - startPage < 4) {
        startPage = Math.max(1, endPage - 4);
    }

    // First page
    if (startPage > 1) {
        pagination.appendChild(createPageItem(1, currentPage));
        if (startPage > 2) {
            const ellipsisLi = document.createElement('li');
            ellipsisLi.className = 'page-item disabled';
            ellipsisLi.innerHTML = '<span class="page-link">...</span>';
            pagination.appendChild(ellipsisLi);
        }
    }

    // Page numbers
    for (let i = startPage; i <= endPage; i++) {
        pagination.appendChild(createPageItem(i, currentPage));
    }

    // Last page
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            const ellipsisLi = document.createElement('li');
            ellipsisLi.className = 'page-item disabled';
            ellipsisLi.innerHTML = '<span class="page-link">...</span>';
            pagination.appendChild(ellipsisLi);
        }
        pagination.appendChild(createPageItem(totalPages, currentPage));
    }

    // Next button
    const nextLi = document.createElement('li');
    nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
    nextLi.innerHTML = `
        <a class="page-link" href="#" data-page="${currentPage + 1}" ${currentPage === totalPages ? 'tabindex="-1" aria-disabled="true"' : ''} aria-label="下一页">
            <i class="mdi mdi-chevron-right" aria-hidden="true"></i>
        </a>
    `;
    pagination.appendChild(nextLi);
}

function createPageItem(pageNumber, currentPage) {
    const li = document.createElement('li');
    li.className = `page-item ${pageNumber === currentPage ? 'active' : ''}`;
    li.innerHTML = `
        <a class="page-link" href="#" data-page="${pageNumber}">${pageNumber}</a>
    `;
    return li;
}

function setupEventListeners() {
    // 搜索和筛选
    document.getElementById('searchInput').addEventListener('input', debounce(() => {
        loadUsers(1);
    }, 500));

    document.getElementById('membershipFilter').addEventListener('change', () => {
        loadUsers(1);
    });

    document.getElementById('statusFilter').addEventListener('change', () => {
        loadUsers(1);
    });

    // 分页点击事件
    document.getElementById('pagination').addEventListener('click', (e) => {
        e.preventDefault();
        const pageLink = e.target.closest('.page-link');
        if (pageLink) {
            const page = parseInt(pageLink.dataset.page);
            if (page && !isNaN(page)) {
                currentPage = page;
                loadUsers(page);
            }
        }
    });

    // 添加用户
    document.getElementById('saveUserBtn').addEventListener('click', () => {
        const form = document.getElementById('addUserForm');
        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());

        fetch('/api/users', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(result => {
            if (result.error) {
                showAlert(result.error, 'danger');
            } else {
                showAlert('用户添加成功', 'success');
                form.reset();
                bootstrap.Modal.getInstance(document.getElementById('addUserModal')).hide();
                loadUsers(currentPage);
            }
        })
        .catch(error => {
            console.error('Error adding user:', error);
            showAlert('添加用户失败，请稍后重试', 'danger');
        });
    });

    // 删除用户
    document.addEventListener('click', (e) => {
        if (e.target.closest('.delete-user')) {
            const userId = e.target.closest('.delete-user').dataset.id;
            if (confirm('确定要删除这个用户吗？此操作不可恢复')) {
                fetch(`/api/users/${userId}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(result => {
                    if (result.error) {
                        showAlert(result.error, 'danger');
                    } else {
                        showAlert('用户删除成功', 'success');
                        loadUsers(currentPage);
                    }
                })
                .catch(error => {
                    showAlert('删除用户失败，请稍后重试', 'danger');
                    showAlert('删除用户失败，请稍后重试', 'danger');
                });
            }
        }
    });

    // 编辑用户
    document.addEventListener('click', (e) => {
        if (e.target.closest('.edit-user')) {
            const userId = e.target.closest('.edit-user').dataset.id;
            fetch(`/api/users/${userId}`)
                .then(response => response.json())
                .then(user => {
                    const form = document.getElementById('editUserForm');
                    form.user_id.value = user.id;
                    form.username.value = user.username;
                    form.email.value = user.email;
                    form.phone.value = user.phone || '';
                    form.membership_level.value = user.membership_level;
                    form.status.value = user.status.toString();
                    
                    const modal = new bootstrap.Modal(document.getElementById('editUserModal'));
                    modal.show();
                });
        }
    });

    // 更新用户
    document.getElementById('updateUserBtn').addEventListener('click', () => {
        const form = document.getElementById('editUserForm');
        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());
        const userId = data.user_id;

        fetch(`/api/users/${userId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(result => {
            if (result.error) {
                showAlert(result.error, 'danger');
            } else {
                showAlert('用户更新成功', 'success');
                bootstrap.Modal.getInstance(document.getElementById('editUserModal')).hide();
                loadUsers(currentPage);
            }
        })
        .catch(error => {
            console.error('Error updating user:', error);
            showAlert('更新用户失败，请稍后重试', 'danger');
        });
    });

    // CSV文件上传
    document.getElementById('uploadCsvBtn').addEventListener('click', () => {
        const fileInput = document.getElementById('csvFile');
        const file = fileInput.files[0];
        if (!file) {
            showAlert('请选择要上传的CSV文件', 'warning');
            return;
        }

        const formData = new FormData();
        formData.append('file', file);

        fetch('/api/upload-users', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(result => {
            if (result.error) {
                showAlert(result.error, 'danger');
            } else {
                showAlert(result.message, result.success ? 'success' : 'warning');
                if (result.errors && result.errors.length > 0) {
                    const errorList = result.errors.join('<br>');
                    document.getElementById('uploadStatus').innerHTML = `
                        <div class="alert alert-warning">
                            <h6>导入详情：</h6>
                            ${errorList}
                        </div>
                    `;
                }
                if (result.success) {
                    fileInput.value = '';
                    loadUsers(currentPage);
                }
            }
        })
        .catch(error => {
            console.error('Error uploading file:', error);
            showAlert('文件上传失败，请稍后重试', 'danger');
        });
    });
}

// 工具函数：防抖
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 显示提示信息
function showAlert(message, type) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed top-0 end-0 m-3`;
    alertDiv.style.zIndex = '1050';
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.body.appendChild(alertDiv);
    setTimeout(() => {
        alertDiv.remove();
    }, 3000);
}
